package com.yihu.wlyy.web.doctor.medical;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.doctor.DoctorMedicalRecordsPart;
import com.yihu.wlyy.entity.doctor.DoctorMedicalRecordsPartItem;
import com.yihu.wlyy.entity.patient.PatientMedicalRecords;
import com.yihu.wlyy.entity.patient.PatientMedicalRecordsItem;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.medicines.MedicalRecordsService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.MessageType;
import com.yihu.wlyy.web.BaseController;

/**
 * 医生端：病历夹控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/medical/record")
public class DoctorMedicalRecordController extends BaseController {

	@Autowired
	private MedicalRecordsService medicalRecordsService;
	@Autowired
	private ConsultTeamService consultTeamService;

	/**
	 * 查询患者片段记录列表
	 * @param patient 患者标识
	 * @param id
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "part_list")
	@ResponseBody
	public String partList(String patient, long id, int pagesize) {
		try {
			JSONArray array = new JSONArray();
			Page<Object> page = medicalRecordsService.findPatientPartsByDoctor(getUID(), patient, id, pagesize);
			for (Object temp : page) {
				Object[] obj = (Object[]) temp;
				if (obj == null || obj.length != 8) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 记录ID
				json.put("id", obj[0]);
				// 记录标识
				json.put("code", obj[1]);
				// 标题
				json.put("title", obj[2]);
				// 主诉
				json.put("symptoms", obj[3]);
				// 图片
				json.put("images", obj[4]);
				// 片段名称
				json.put("part_name", obj[5]);
				// 片段内容
				json.put("content", obj[6]);
				// 添加时间
				json.put("czrq", DateUtil.dateToStrLong((Date) obj[7]));
				array.put(json);
			}
			return write(200, "查询成功！", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 查询患者病历记录列表
	 * @param patient 患者标识
	 * @param id
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "record_list")
	@ResponseBody
	public String recordList(String patient, long id, int pagesize) {
		try {
			JSONArray array = new JSONArray();
			Page<PatientMedicalRecords> page = medicalRecordsService.findRecordsByPatient(patient, id, pagesize);
			for (PatientMedicalRecords temp : page) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 记录ID
				json.put("id", temp.getId());
				// 记录标识
				json.put("code", temp.getCode());
				// 标题
				json.put("title", temp.getTitle());
				// 记录医生姓名
				json.put("doctorName", temp.getDoctorName());
				// 添加时间
				json.put("czrq", DateUtil.dateToStrLong(temp.getCzrq()));
				array.put(json);
			}
			return write(200, "查询成功！", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 查询病历记录明细
	 * @param record 病历记录标识
	 * @return
	 */
	@RequestMapping(value = "info")
	@ResponseBody
	public String info(String record) {
		try {
			JSONObject jsonObject = new JSONObject();
			JSONArray array = new JSONArray();
			// 查询主诉和图片信息
			PatientMedicalRecords pmr = medicalRecordsService.findRecordByCode(record);
			// 查询片段信息
			List<PatientMedicalRecordsItem> list = medicalRecordsService.findRecordItemByCode(record);
			for (PatientMedicalRecordsItem temp : list) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 片段名称
				json.put("partName", temp.getPartName());
				// 片段内容
				json.put("content", temp.getContent());
				array.put(json);
			}
			String[] images = null;
			if (StringUtils.isNotEmpty(pmr.getImages())) {
				images = pmr.getImages().split(",");
			}
			// 主诉
			jsonObject.put("symptoms", pmr.getSymptoms());
			// 图片
			jsonObject.put("images", images);
			// 片段列表
			jsonObject.put("list", array);
			return write(200, "查询成功！", "data", jsonObject);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 患者咨询记录查询接口
	 * @return
	 */
	@RequestMapping(value = "consult_list")
	@ResponseBody
	public String consultList(String patient, long id, int pagesize) {
		try {
			JSONArray array = new JSONArray();
			Page<Consult> page = consultTeamService.findConsultRecordByPatientType(patient, id, pagesize);
			for (Consult temp : page) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 咨询ID
				json.put("id", temp.getId());
				// 咨询标识
				json.put("code", temp.getCode());
				// 咨询类型：1三师咨询，2视频咨询，3图文咨询，4公共咨询，5病友圈
				json.put("type", temp.getType());
				// 主诉/症状
				json.put("symptoms", temp.getSymptoms());
				// 咨询图片URL，多图以逗号分隔
				json.put("images", temp.getTitle());
				// 添加时间
				json.put("czrq", DateUtil.dateToStrLong(temp.getCzrq()));
				array.put(json);
			}
			return write(200, "查询成功！", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 查询医生片段信息
	 * @return
	 */
	@RequestMapping(value = "parts")
	@ResponseBody
	public String parts() {
		try {
			return write(200, "查询成功！", "list", medicalRecordsService.findAllDoctorParts(getUID()));
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 添加医生片段信息
	 * @param name
	 * @return
	 */
	@RequestMapping(value = "add_part")
	@ResponseBody
	public String addPart(String name) {
		try {
			DoctorMedicalRecordsPart part = medicalRecordsService.addPart(getUID(), name);
			if (part == null) {
				return error(-1, "保存失败！");
			} else {
				return write(200, "保存成功！", "code", part.getCode());
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}

	/**
	 * 添加片段内容
	 * @param part 片段标识
	 * @param content 片段内容
	 * @return
	 */
	@RequestMapping(value = "add_part_item")
	@ResponseBody
	public String addPartItem(String part, String content) {
		try {
			DoctorMedicalRecordsPartItem item = medicalRecordsService.addPartItem(getUID(), part, content);
			if (item == null) {
				return error(-1, "保存失败！");
			} else {
				return write(200, "保存成功！", "id", item.getId());
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}

	/**
	 * 添加患者片段记录
	 * @param patient
	 * @param part
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "add_part_record")
	@ResponseBody
	public String addPartRecord(String patient, String part, String content) {
		try {
			medicalRecordsService.addPartRecord(getUID(), patient, part, content);
			return success("保存成功！");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}

	/**
	 * 患者片段记录修改接口
	 * @param record 记录标识
	 * @param part 
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "modify_part_record")
	@ResponseBody
	public String modifyPartRecord(String record, String content) {
		try {
			// 查询片段记录内容
			PatientMedicalRecords pmr = medicalRecordsService.findRecordByCode(record);
			if (pmr == null || !StringUtils.equals(pmr.getDel(), "1")) {
				return error(-1, "片段记录不存在或已删除！");
			} else if (pmr.getType() != 2) {
				return error(-1, "不允许修改病历记录！");
			} else if (!StringUtils.equals(pmr.getDoctor(), getUID())) {
				return error(-1, "只允许修改自己的片段记录！");
			}
			medicalRecordsService.modifyPartRecord(pmr, content);
			return success("保存成功！");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}

	/**
	 * 删除指定的患者片段记录
	 * @param record 记录标识
	 * @return
	 */
	@RequestMapping(value = "del_part_record")
	@ResponseBody
	public String delPartRecord(String record) {
		try {
			PatientMedicalRecords temp = medicalRecordsService.findRecordByCode(record);
			if (temp == null) {
				return error(-1, "该片段不存在！");
			}
			if (temp.getType() != 2) {
				return error(-1, "当前片段不允许删除！");
			}
			if (!StringUtils.equals(temp.getDoctor(), getUID())) {
				return error(-1, "只允许删除自己编写的片段记录！");
			}
			medicalRecordsService.deletePartRecord(getUID(), temp.getPatient(), record);
			return success("片段已删除！");
		} catch (Exception e) {
			error(e);
			return error(-1, "删除失败！");
		}
	}

	/**
	 * 添加病历记录
	 * @param patient
	 * @param consult
	 * @param title
	 * @param parts
	 * @return
	 */
	@RequestMapping(value = "add_record")
	@ResponseBody
	public String addRecord(String patient, String consult, String title, String parts) {
		try {
			PatientMedicalRecords temp = medicalRecordsService.addRecord(getUID(), patient, consult, title, parts);
			//推送消息给患者
			PushMsgTask.getInstance().put(patient, MessageType.MESSAGE_TYPE_PATIENT_MEDICAL_RECORD.P_MR_01.name(), MessageType.MESSAGE_TYPE_PATIENT_MEDICAL_RECORD.病历夹.name(), MessageType.MESSAGE_TYPE_PATIENT_MEDICAL_RECORD.您有新的病历记录.name(), temp.getCode());
			return success("保存成功！");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}

}
